package com.lingtianyu.tech.springcloud.grayzone.grey.config;

import com.lingtianyu.tech.springcloud.grayzone.grey.annotation.SpringCloudGrey;
import com.lingtianyu.tech.springcloud.grayzone.grey.interceptor.GreyRequestInterceptor;
import com.lingtianyu.tech.springcloud.grayzone.grey.interceptor.SpringCloudGreyLingtianyuRestTemplateCustomizer;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(RestTemplate.class)
public class SpringCloudGreyLingtianyuAutoConfig {
    @Autowired(required = false)
    @SpringCloudGrey
    private List<RestTemplate> restTemplates = Collections.emptyList();

    @Bean
    public SmartInitializingSingleton springCloudLingtianyuOpenapiRestTemplateInitializerDeprecated(
            final SpringCloudGreyLingtianyuRestTemplateCustomizer springcloudGreyLingtianyuRestTemplateCustomizer) {
        return () -> {
            for (RestTemplate restTemplate : SpringCloudGreyLingtianyuAutoConfig.this.restTemplates) {
                springcloudGreyLingtianyuRestTemplateCustomizer.customize(restTemplate);
            }
        };
    }

    @Bean
    public GreyRequestInterceptor springCloudLingtianyuOpenapiInterceptor() {
        return new GreyRequestInterceptor();
    }

    @Bean
    @ConditionalOnMissingBean
    public SpringCloudGreyLingtianyuRestTemplateCustomizer springCloudLingtianyuOpenapiRestTemplateCustomizer(GreyRequestInterceptor greyRequestInterceptor) {
        return restTemplate -> {
            List<ClientHttpRequestInterceptor> list = new ArrayList<>(restTemplate.getInterceptors());
            list.add(greyRequestInterceptor);
            restTemplate.setInterceptors(list);
        };
    }
}
